﻿using CommonUtils;
using Microsoft.VisualStudio.Shell;
using System;
using System.Windows.Forms;
using System.Linq;

namespace CodeAssistant.Commands.IDE
{
    class SameFolderNames
    {
        public static void Handler(object sender, EventArgs e)
        {
            ThreadHelper.ThrowIfNotOnUIThread();

            var slnPath = WindowsUtil.SelectFile("*.sln");
            if (!FileUtil.Exists(slnPath))
            {
                MessageBox.Show("请重新选择！");
                return;
            }

            var slnFolder = FileUtil.GetFolder(slnPath);
            if (!GitUtil.IsRepository(slnFolder))
            {
                MessageBox.Show("为防止代码丢失，仅支持git版本控制的项目！");
                return;
            }

            MessageBox.Show("请确保项目处于关闭状态，文件夹改名不会受阻！");

            var lines = FileUtil.GetLines(slnPath);
            lines = lines.Where(m => m.StartsWith("Project")).ToArray();

            //获取参数
            var srcPaths = lines.Select(m => m.Split('"')[5]).ToArray();
            var srcFolders = new string[srcPaths.Length];
            var targetFolders = new string[srcPaths.Length];
            var targetPaths = new string[srcPaths.Length];
            for (int index = 0; index < srcPaths.Length; index++)
            {
                var srcPath = srcPaths[index];
                var cells = srcPath.Split('\\');
                var srcFolder = cells[0];
                var name = cells[1];
                var targetFolder = name.Remove(".csproj");

                srcFolders[index] = slnFolder.Combine(srcFolder);
                targetFolders[index] = slnFolder.Combine(targetFolder);
                targetPaths[index] = targetFolder + '\\' + name;
            }

            //修改csproj,sln
            var slnText = FileUtil.GetText(slnPath);
            for (int index1 = 0; index1 < srcPaths.Length; index1++)
            {
                var csprojPath = slnFolder.Combine(srcPaths[index1]);
                var csprojText = FileUtil.GetText(csprojPath);
                for (int index2 = 0; index2 < srcPaths.Length; index2++)
                    csprojText = csprojText.Replace(srcPaths[index2], targetPaths[index2]);
                FileUtil.Save(csprojPath, csprojText);
                slnText = slnText.Replace(srcPaths[index1], targetPaths[index1]);
            }
            FileUtil.Save(slnPath, slnText);

            //修改文件夹
            srcFolders.For((index, srcFolder) => GitUtil.Move(slnFolder, srcFolder, targetFolders[index]));

            MessageBox.Show("处理完成！");
        }
    }
}
